<template>
<div style="padding:20px;background:#fff">
    <el-form
    ref="downloadFormRef"
    :model="downloadForm"
    :rules="validateRules"
    label-width="auto"
    label-position="top"
  >
    <el-form-item label="组织名称(groupId)" prop="groupId">
      <el-input v-model="downloadForm.groupId" style="width:300px" @input="changeProjectValue"/>
    </el-form-item>
    <el-form-item label="项目名称(artifactId)" prop="artifactId">
      <el-input v-model="downloadForm.artifactId" style="width:300px" @input="changeProjectValue"/>
    </el-form-item>
    <el-form-item label="包名(package)" prop="packageName">
      <el-input v-model="downloadForm.packageName" style="width:300px"  @input="changePackageValue"/>
    </el-form-item>
    <el-form-item label="中间件">
      <el-checkbox-group v-model="downloadForm.middleware">
        <el-checkbox-button label="springsecurity" name="type" >SpringSecurity</el-checkbox-button>
        <el-checkbox-button label="swagger3" name="type" >Swagger3</el-checkbox-button>
        <el-checkbox-button label="redis" name="type" >Redis</el-checkbox-button>
        <el-checkbox-button label="mybatis" name="type">Mybatis</el-checkbox-button>
        <el-checkbox-button label="rabbitmq" name="type" disabled>RabbitMQ</el-checkbox-button>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item label="数据库">
      <el-radio-group v-model="downloadForm.database">
        <el-radio-button border label="mysql" >MySQL</el-radio-button>
        <el-radio-button border label="h2" disabled >H2</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">{{$t('data.button.download')}}</el-button>
      <el-button @click="reset">{{$t('data.button.reset')}}</el-button>
    </el-form-item>
  </el-form>
  <div class="full-fixed" v-if="showDownload">
  <el-progress type="circle" :percentage="downloadPercent" status="success" :stroke-width="15" :width='250' v-if="downloadPercent==100">
      <el-button type="success" :icon="Check" circle style="width:50px;height:50px;font-size:20px;"></el-button>
      <br />
      <span style="margin-top:15px;font-size:14px;">下载成功</span>
    </el-progress>
    <el-progress type="dashboard" :percentage="downloadPercent" :stroke-width="15" :width='250' v-else>
      <template #default="{ percentage }">
        <span class="percentage-value">{{ percentage }}%</span>
      </template>
    </el-progress>
    </div>
</div>
</template>
<script setup>
import {reactive,ref} from 'vue'
import { Check} from '@element-plus/icons-vue'
import {message} from '@/plugin/elementplus'
import userApi from '@/api/user'
const downloadFormRef=ref(null)
const downloadForm=reactive({})
const packageNameChanged=ref(false)
const downloadPercent=ref(0)
const showDownload=ref(false)
const reset=function(){
    downloadForm.project='SECURITY_BOOT'
    downloadForm.middleware=['springsecurity','mybatis']
    downloadForm.database='mysql'
    downloadFormRef.value?downloadFormRef.value.resetFields():''
}
reset()
const onProcess=function(process){
    downloadPercent.value=parseFloat(process);
    if(downloadPercent.value==100){
        setTimeout(()=>{
            showDownload.value=false
        },2000)
    }
}
const onSubmit=function(){
    console.log(downloadForm)
    downloadFormRef.value.validate(valid=>{
        console.log(valid)
        if(valid){
            showDownload.value=true
            downloadPercent.value=0
            userApi.downloadSourceCode(downloadForm,onProcess).then(d=>{
                if(d.type.indexOf('application/json')>-1){
                    d.text().then(eee=>{
                        message({
                            showClose: true,
                            message: JSON.parse(eee).message,
                            type: 'error',
                        })
                    })
                    showDownload.value=false
                    downloadPercent.value=0
                    return;
                }
                var filename=downloadForm.artifactId+".zip"
                if (typeof window.chrome !== 'undefined') {
                    // Chrome version
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(d);
                    link.download = filename;
                    link.click();
                } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE version
                    var blob = new Blob([d], { type: 'application/force-download' });
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    // Firefox version
                    var file = new File([d], filename, { type: 'application/force-download' });
                    window.open(URL.createObjectURL(file));
                }
            }).catch(e=>{
                console.log('e',e)
            })
        }
    })
}
const changeProjectValue=function(){
    if(!packageNameChanged.value){
        let name='';
        if(downloadForm.groupId){
            name=downloadForm.groupId
        }
        if(downloadForm.artifactId){
            name=(name.length>0?(name+'.'):'')+downloadForm.artifactId;
        }
        downloadForm.packageName=name
    }
}
const changePackageValue=function(){
    packageNameChanged.value=true
}
const validateRules={
                groupId:[
                    {
                        required: true,
                        message: '请输入组织名称(groupId)',
                        trigger: 'blur',
                    },
                    {
                        max: 200,
                        message: '不能超过200字',
                        trigger: 'blur',
                    },
                    {
                        validator(rule, value) {
                            // let re =/^(?!\.)[A-Za-z0-9_\.-]+(?<!\.)$/;
                            let re =new RegExp('^(?!_|\\.|-)[A-Za-z0-9_\\.-]+(?<!_|\\.|-)$');
                            return re.test(value);
                        },
                        message: '组织名称不符合规则',
                        trigger: 'change',
                    }
                ],
                artifactId:[
                    {
                        required: true,
                        message: '请输入项目名称(artifactId)',
                        trigger: 'blur',
                    },
                    {
                        max: 200,
                        message: '不能超过200字',
                        trigger: 'blur',
                    },
                    {
                        validator(rule, value) {
                            let re =new RegExp('^[A-Za-z0-9_-]+$');
                            return re.test(value);
                        },
                        message: '项目名称不符合规则',
                        trigger: 'change',
                    }
                ],
                packageName:[
                    {
                        required: true,
                        message: '请输入包名(package)',
                        trigger: 'blur',
                    },
                    {
                        max: 200,
                        message: '不能超过200字',
                        trigger: 'blur',
                    },
                    {
                        validator(rule, value) {
                            let re =new RegExp('^(?!_|\\.|-)[A-Za-z0-9_\\.-]+(?<!_|\\.|-)$');
                            return re.test(value);
                        },
                        message: '包名不符合规则',
                        trigger: 'change',
                    }
                ],
            }
</script>
<style lang="scss" scoped>
.el-radio-group {
  margin-right: 4px;
}
.full-fixed{
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    vertical-align: middle;
    padding-top:20%;
    text-align: center;
    z-index: 999;
    background:rgba(0, 0, 0, 0.7);
}
</style>